import { onMounted, onUnmounted, Ref, ref } from "vue"
// import CardScanner from "@/utils/cardScanner"
export default function useCardScanner(ScannerDom: Ref<HTMLInputElement>) {
  const cardString = ref("")
  // let cardScannerInstance: CardScanner

  // let intervalId
  const handleKeypress = (e) => {
    console.log(e)
    if (e.key === "Enter") {
      console.log(e.key)
      cardString.value = ScannerDom.value.value;
      ScannerDom.value.value = "";
    }
  }

  onMounted(() => {
    console.log(ScannerDom.value)
    ScannerDom.value.addEventListener("keypress", handleKeypress)
    // cardScannerInstance = new CardScanner({
    //   finish(card) {
    //     cardString.value = card
    //   }
    // })
  })
  onUnmounted(() => {
    ScannerDom.value.removeEventListener("keypress", handleKeypress)
    // cardScannerInstance.destroy()
  })
  // 目标点聚焦
  // const maxTime = 3
  // let time = maxTime
  // function resetTime() {
  //   time = maxTime
  // }
  // onMounted(() => {
  //   document.addEventListener("keydown", resetTime)
  //   document.addEventListener("mousedown", resetTime)
  //   intervalId = setInterval(function () {
  //     time--
  //     if (time <= 0) {
  //       // TODO:
  //       time = maxTime
  //       ScannerDom.value.focus()
  //     }
  //   }, 1000)
  // })
  // onUnmounted(() => {
  //   if (intervalId) {
  //     clearInterval(intervalId)
  //     document.removeEventListener("keydown", resetTime)
  //     document.removeEventListener("keydown", resetTime)
  //   }
  // })
  const handleToBlur = () => {
    console.log("handle to blur")
    ScannerDom.value.focus()
  }
  return {
    cardString,
    handleToBlur
  }
}
